﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Windows.Threading;

namespace RIA.NTiersApp.Extensions
{
    public class ListBoxDoubleClickBehavior : Behavior<ListBox>
    {
        private readonly MouseClickManager _gridClickManager;
        public event EventHandler<MouseButtonEventArgs> DoubleClick;
        public ListBoxDoubleClickBehavior ()
        {
            _gridClickManager = new MouseClickManager ( 300 );
            _gridClickManager.DoubleClick += new MouseButtonEventHandler ( _gridClickManager_DoubleClick );
        }
        void _gridClickManager_DoubleClick ( object sender, MouseButtonEventArgs e )
        {
            if ( DoubleClick != null )
                DoubleClick ( sender, e );
            
        }

        protected override void OnAttached ()
        {
            base.OnAttached ();
            AssociatedObject.MouseLeftButtonUp +=  AssociatedObject_MouseLeftButtonUp ;
        }

        void AssociatedObject_MouseLeftButtonUp ( object sender, MouseButtonEventArgs e )
        {
             ListBox list = sender as ListBox;
             
            if (list!=null && list.SelectedIndex>=0  )
            {
                _gridClickManager.HandleClick ( sender, e );
            }
        }

        protected override void OnDetaching ()
        {
            base.OnDetaching ();
            AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;

        }
    }
}
